package com.ruoyi.project.remake.controller.api;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.framework.security.LoginUser;
import com.ruoyi.framework.security.service.TokenService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.common.component.HaoleiProperties;
import com.ruoyi.project.common.utils.WordUtils;
import com.ruoyi.project.remake.domain.ApplyDocument;
import com.ruoyi.project.remake.domain.PayMent;
import com.ruoyi.project.remake.domain.TBorrowApproval;
import com.ruoyi.project.remake.domain.TCaseMain;
import com.ruoyi.project.remake.domain.constant.InitConstant;
import com.ruoyi.project.remake.domain.dto.*;
import com.ruoyi.project.remake.domain.enmu.RemakeSourceState;
import com.ruoyi.project.remake.domain.query.BorrowApprovalQuery;
import com.ruoyi.project.remake.domain.query.PrintDetailsQuery;
import com.ruoyi.project.remake.domain.query.SelfMachine;
import com.ruoyi.project.remake.domain.query.TPaperCaseQuery;
import com.ruoyi.project.remake.domain.vo.*;
import com.ruoyi.project.remake.service.*;
import com.ruoyi.project.system.domain.SysDictData;

import com.ruoyi.project.system.service.ISysConfigService;
import com.ruoyi.project.system.service.ISysDictDataService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.IOException;
import java.util.*;


@Api("医生打印端文档")
@RestController
@RequestMapping("/api/remaked/print")
public class PrintController extends BaseController {

    @Autowired
    private ITApplyStatusService tApplyStatusService;
    @Autowired
    private ITCaseMainService tCaseMainService;
    @Autowired
    private ITPaperCaseService tPaperCaseService;
    @Autowired
    private ITBorrowApprovalService tBorrowApprovalService;
    @Autowired
    private ITRemakeCaseDetailsService tRemakeCaseDetailsService;
    @Autowired
    private ISysDictDataService sysDictDataService;
    @Autowired
    private ISysConfigService sysConfigService;

    @Autowired
    private TokenService tokenService;
    @Autowired
    private IPayMentService payMentService;

    @Autowired
    private IApplyDocumentService applyDocumentService;

    @Autowired
    private ServerConfig serverConfig;

    /**
     * 打印程序段复印模块列表
     *
     * @param copyCaseDto
     * @return
     */
    @ApiOperation("复印模块查询")
    @GetMapping("/copyList")
    public TableDataInfo list(CopyCaseDto copyCaseDto) {
        startPage();
        List<CopyCaseVo> list = tApplyStatusService.selectCopyPrintList(copyCaseDto);
        return getDataTable(list);
    }

    /**
     * 获取某一个病例打印的详情
     *
     * @param query
     * @return
     */
    @ApiOperation("获取某一个病例打印的详情")
    @GetMapping("/details")
    public AjaxResult details(PrintDetailsQuery query) {
        List<PrintDetailsVo> printDetailsVoList = tRemakeCaseDetailsService.selectCopyList(query);
        RemarkPrintDetailsVo detailsVo = tRemakeCaseDetailsService.loadIndexModel(query.getCaseMainId(), printDetailsVoList);
        return AjaxResult.success(detailsVo);
    }

    /**
     * 获取某一个病例打印的详情
     *
     * @param query
     * @return
     */
    @ApiOperation("获取某一个病例打印的详情")
    @GetMapping("/detailsList")
    public AjaxResult detailsList(PrintDetailsQuery query) {
        List<PrintDetailsVo> printDetailsVoList = tRemakeCaseDetailsService.selectCopyList(query);
        return AjaxResult.success(printDetailsVoList);
    }

    /**
     * 根据申请id获取打印内容的PDF文件
     *
     * @return
     */
    @ApiOperation("根据申请id获取打印内容的PDF文件")
    @GetMapping("/printPDF")
    public AjaxResult printPDF(ApplyDocument document) {
        String url = tRemakeCaseDetailsService.printPDF(document.getId());
        return AjaxResult.success(url);
    }

    /**
     * 获取打印份数的接口
     *
     * @return
     */
    @ApiOperation("获取打印份数的接口")
    @GetMapping("/printNumber")
    public AjaxResult printNumber() {
        String configByKey = sysConfigService.selectConfigByKey(InitConstant.PRINT_NUMBER);
        List<Integer> list = new ArrayList<>();
        try {
            Integer number = Integer.valueOf(configByKey);
            for (int i = 1; i <= number; i++) {
                list.add(i);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.success(list);
    }

    /**
     * 获取支付类型的接口
     *
     * @return
     */
    @ApiOperation("获取支付类型的接口")
    @GetMapping("/payTypeList")
    public AjaxResult payTypeList() {
        List<SysDictData> sysDictDataList = sysDictDataService.selectDictDataByType(InitConstant.PAY_TYPE);
        List<String> list = new ArrayList<>();
        try {
            for (SysDictData data : sysDictDataList) {
                list.add(data.getDictLabel());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.success(list);
    }

    /**
     * 获取支付类型的接口
     *
     * @return
     */
    @ApiOperation("获取人员关系类型的的接口")
    @GetMapping("/relationList")
    public AjaxResult relationList() {
        List<SysDictData> sysDictDataList = sysDictDataService.selectDictDataByType(InitConstant.RELATION);
        List<String> list = new ArrayList<>();
        try {
            for (SysDictData data : sysDictDataList) {
                list.add(data.getDictLabel());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.success(list);
    }

    /**
     * 获取支付类型的接口
     *
     * @return
     */
    @ApiOperation("获取人员关系类型的的接口")
    @GetMapping("/copySubjectList")
    public AjaxResult copySubjectList() {
        List<SysDictData> sysDictDataList = sysDictDataService.selectDictDataByType(InitConstant.MATTER);
        List<String> list = new ArrayList<>();
        try {
            for (SysDictData data : sysDictDataList) {
                list.add(data.getDictLabel());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.success(list);
    }

    /**
     * 收款接口
     *
     * @return
     */
    @ApiOperation("收款接口")
    @PostMapping("/payMent")
    public AjaxResult payMent(PayMent payMent) {
        payMent.setCreateBy("1L");
        payMent.setCreateTime(new Date());
        return toAjax(payMentService.insertPayMent(payMent));
    }

    /**
     * 病例详情
     *
     * @return
     */
    @ApiOperation("病例详情  ")
    @GetMapping("/caseDetails")
    public AjaxResult caseDetails(Long id) {
        CaseMainVo caseMain = tCaseMainService.selectTCaseMainById(id);
        return AjaxResult.success(caseMain);
    }

    /**
     * 保存申请单  20230328
     *
     * @return
     */
    @ApiOperation("保存申请单 ")
    @PostMapping("/saveApplyDocument")
    public AjaxResult saveApplyDocument(ApplyDocument applyDocument) {
        applyDocumentService.insertApplyDocument(applyDocument);
        return AjaxResult.success(applyDocument.getId());
    }

    /**
     * 模板
     *
     * @return
     */
    @ApiOperation("测试Word模板  ")
    @GetMapping("/printWord")
    public AjaxResult printWord(Long id) {
        try {
            Map<String, Object> result = applyDocumentService.getApply(id);
            //WordUtils.generateWord(result,"myword.ftl","myword.doc");
            return AjaxResult.success(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.success();
    }

    /**
     * 计算病例打印费用
     *
     * @param cardNumber
     * @return
     */
    @ApiOperation("计算病例打印费用")
    @GetMapping("/printMoney/{cardNumber}")
    public AjaxResult list(@PathVariable String cardNumber) {

        PrintMoney printMoney = tCaseMainService.getTotileMoney(cardNumber);
        return AjaxResult.success(printMoney);
    }

    /**
     * 通过申请查看所需要打印的病例信息
     *
     * @param selfMachine
     * @return
     */
    @ApiOperation("打印病例")
    @GetMapping("/queryByCard")
    public AjaxResult queryByCard(SelfMachine selfMachine) {
        TCaseMain tCaseMain = new TCaseMain();
        tCaseMain.setCardId(selfMachine.getCardId());
        tCaseMain.setMedicalCardId(selfMachine.getMedicalCardId());
        if (ObjectUtil.isNull(selfMachine.getCardId()) && ObjectUtil.isNull(selfMachine.getMedicalCardId())) {
            return AjaxResult.success();
        }
        List<TCaseMain> list = tCaseMainService.selectSelfFrontList(tCaseMain);
        return AjaxResult.success(list);
    }

    /**
     * 病例查询入口
     *
     * @param caseMainDto
     * @return
     */
    @ApiOperation("病例查询入口,type 为1代表翻拍病查询，type为0为病例信息查询")
    @GetMapping("/list")
    public TableDataInfo list(CaseMainDto caseMainDto) {

        //如果需要对接第三方，则先进行存储
        if (RemakeSourceState.HOSPITAL.getValue().toString().equals(caseMainDto.getType())) {
            //检查数据库是否已经存在
            TCaseMain thrid = new TCaseMain();
            thrid.setCardNumber(caseMainDto.getCardNumber());
            List<TCaseMain> caseMainThridList = tCaseMainService.selectTCaseMainList(thrid);
            if (ObjectUtil.isEmpty(caseMainThridList) || caseMainThridList.size() == 0) {
                String dataList = HttpUtils.sendGet(InitConstant.THRID_PARTY, "CardNumber="+caseMainDto.getCardNumber());
                tCaseMainService.coverCopyList(dataList);
            }
        }
        startPage();
        List<CopyCaseVo> list = tCaseMainService.selectTCaseMainFrontList(caseMainDto);
        return getDataTable(list);
    }



    /**
     * 查询借阅审批列表
     *
     * @param borrowApprovalQuery
     * @return
     */
    @ApiOperation("借阅审批查询")
    @GetMapping("/approvalList")
    public TableDataInfo list(BorrowApprovalQuery borrowApprovalQuery) {
        startPage();
        List<TBorrowApproval> list = tBorrowApprovalService.selectAllFrontApprovalList(borrowApprovalQuery);
        return getDataTable(list);
    }

    @ApiOperation("查询病例下分类列表")
    @GetMapping(value = "/tRemakeCaseType")
    public AjaxResult tRemakeCaseType() {
        return AjaxResult.success(sysDictDataService.selectDictDataByType(InitConstant.CLASS_TYPE_DICT));
    }

    @ApiOperation("根据病例ID和分类查询病例详情")
    @GetMapping(value = "/tRemakeCaseDetails")
    public AjaxResult tRemakeCaseDetails(CaseDetailDto caseDetailDto) {
        AjaxResult ajaxResult = tRemakeCaseDetailsService.tRemakeCaseDetails(caseDetailDto);
        return ajaxResult;
    }

    @ApiOperation("增加借阅审批")
    @PostMapping(value = "/addBorrowApproval")
    public AjaxResult addBorrowApproval(BorrowApprovalDto borrowApprovalDto) {
        AjaxResult ajaxResult = tBorrowApprovalService.frontCreatBorrowApproval(borrowApprovalDto);
        return ajaxResult;
    }

    @ApiOperation("借阅审批")
    @GetMapping(value = "/examine")
    public AjaxResult examine(BorrowApprovalExamineDto borrowApprovalExamineDto) {
        AjaxResult ajaxResult = tBorrowApprovalService.examine(borrowApprovalExamineDto);
        return ajaxResult;
    }

    @ApiOperation("打印分类")
    @GetMapping(value = "/printclass")
    public AjaxResult examine() {

        List<SysDictData> sysDictDataList = sysDictDataService.selectDictDataByType(InitConstant.PRINT_CLASS);
        return AjaxResult.success(sysDictDataList);
    }

    @ApiOperation("打印分类")
    @GetMapping(value = "/printclassnew")
    public AjaxResult printclassnew() {

        List<SysDictData> sysDictDataList = sysDictDataService.selectDictDataByType("print_class");
        return AjaxResult.success(sysDictDataList);
    }

    @ApiOperation("增加收款明细")
    @PostMapping(value = "/addcollectiondetails")
    public AjaxResult addBorrowApproval(CollectiondetailsDto collectiondetailsDto) {

        return AjaxResult.success();
    }

    @ApiOperation("测试上传模块")
    @GetMapping(value = "/testUpload")
    public AjaxResult testUpload() {
        //使用上传文件的方式，上传到服务器上。
        //将File文件转化为MultipartFile
        //base64 转化到服务器上某一个路径，
        String a = FileUtils.file2Str("D:\\2222.png");
        System.out.println(RuoYiConfig.getProfile());
        RuoYiConfig ruoYiConfig = new RuoYiConfig();

        System.out.println(ruoYiConfig.getName());
        System.out.println(ruoYiConfig.getCopyrightYear());
        String tmpFilePath = RuoYiConfig.getThridfile() + "/" + "123445" + System.currentTimeMillis() + ".png";
        FileUtils.str2File(a, tmpFilePath);
        // 上传文件路径
        String filePath = RuoYiConfig.getUploadPath();
        // 上传并返回新文件名称
        File file = new File(tmpFilePath);
        String fileName = null;
        try {
            fileName = FileUploadUtils.upload(filePath, FileUtils.getMultipartFile(file));
        } catch (IOException e) {
            e.printStackTrace();
        }
        FileUtils.deleteFile(tmpFilePath);
        String url = serverConfig.getUrl() + fileName;

        AjaxResult ajax = AjaxResult.success();
        ajax.put("fileName", fileName);
        ajax.put("url", url);
        return ajax;
    }


}
